package cn.itcast.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class LoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1 获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        // 2 获取authorization参数
        String authorization = request.getQueryParams().getFirst("authorization");
        // 3 判断是否为admin
        if ("admin".equals(authorization)) {
            // 放行
            return chain.filter(exchange);
        }
        ServerHttpResponse response = exchange.getResponse();
        // 4 设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        // 5 拦截
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
